package projectx.util.log4j;

import org.apache.log4j.Priority;
import org.apache.log4j.helpers.FormattingInfo;
import org.apache.log4j.helpers.PatternConverter;
import org.apache.log4j.helpers.PatternParser;
import org.apache.log4j.spi.LoggingEvent;

public class ProjectXPatternParser extends PatternParser {

	/**
	 * Constructor.
	 */
	public ProjectXPatternParser(String pattern) {

		super(pattern);
	}

	/**
	 * Convert finalizer. This actually adds Converter object with calling
	 * super.addConverter(). This method of this class handles only %s options -
	 * all the others are dispatched to the same method in the parent class.
	 */
	protected void finalizeConverter(char c) {

		switch (c) {

		case 's':
			super.addConverter(new SeverityPatternConverter(
					super.formattingInfo));
			super.currentLiteral.setLength(0);
			break;

		default:
			super.finalizeConverter(c);
			break;
		}
	}

	// ----------------------------------------------------------------------------------------------
	// Severity pattern converter
	//
	// ----------------------------------------------------------------------------------------------
	private static class SeverityPatternConverter extends PatternConverter {

		// --- Constructor ---
		SeverityPatternConverter(FormattingInfo formattingInfo) {

			super(formattingInfo);
		}

		// --- Converter ---
		protected String convert(LoggingEvent event) {

			char sev;

			switch (event.getLevel().toInt()) {

			case Priority.FATAL_INT:
				sev = '1';
				break;

			case Priority.ERROR_INT:
				sev = '2';
				break;

			case Priority.WARN_INT:
				sev = '3';
				break;

			case Priority.INFO_INT:
				sev = '4';
				break;

			default:
				sev = '-';
				break;
			}

			return "Severity " + sev;
		}
	}
}
